﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;

public class InputManager : MonoBehaviour
{
    public static InputManager Instance { get; private set; }

    // 映射：目标名称 -> 对应轨道控制器
    public Dictionary<string, LaneController> laneMap = new Dictionary<string, LaneController>();

    // 映射：手指 -> 当前轨道
    private Dictionary<Finger, LaneController> fingerToLaneMap = new Dictionary<Finger, LaneController>();

    // 手指滑动信息（用于 Flick 判断）
    private class FingerSwipeInfo
    {
        public Vector2 startPos;
        public float startTime;
    }

    private Dictionary<Finger, FingerSwipeInfo> fingerSwipeData = new Dictionary<Finger, FingerSwipeInfo>();

    // Flick 判定参数
    private const float flickMinDistance = 20f;     // 最小滑动距离（像素）
    private const float flickMaxDuration = 0.8f;    // 最大滑动时间（秒）

    public void RegisterLaneController(string targetName, LaneController controller)
    {
        if (!laneMap.ContainsKey(targetName))
        {
            laneMap.Add(targetName, controller);
        }
    }

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
    }

    private void OnEnable()
    {
        EnhancedTouchSupport.Enable();
        Touch.onFingerDown += HandleFingerDown;
        Touch.onFingerUp += HandleFingerUp;
        Touch.onFingerMove += HandleFingerMove;
    }

    private void OnDisable()
    {
        Touch.onFingerDown -= HandleFingerDown;
        Touch.onFingerUp -= HandleFingerUp;
        Touch.onFingerMove -= HandleFingerMove;
        EnhancedTouchSupport.Disable();
    }

    private void HandleFingerDown(Finger finger)
    {
        Ray ray = Camera.main.ScreenPointToRay(finger.screenPosition);
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            if (hit.collider != null && hit.collider.name.StartsWith("Target"))
            {
                if (laneMap.TryGetValue(hit.collider.name, out LaneController lane))
                {
                    fingerToLaneMap[finger] = lane;
                    
                    lane.OnTouchFromInput();
                    
                    
                    fingerSwipeData[finger] = new FingerSwipeInfo
                    {
                        startPos = finger.screenPosition,
                        startTime = Time.time
                    };
                }
            }
        }
    }

    private void HandleFingerMove(Finger finger)
    {
        if (!fingerToLaneMap.TryGetValue(finger, out LaneController activeLane)) return;

        if (activeLane != null && activeLane.hasLongNote)
        {
            Ray ray = Camera.main.ScreenPointToRay(finger.screenPosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                if (hit.collider != null && hit.collider.name.StartsWith("Target"))
                {
                    if (laneMap.TryGetValue(hit.collider.name, out LaneController newLane))
                    {
                        if (newLane != activeLane)
                        {
                            // 离开旧轨道
                            activeLane.OnTouchUp();
                            activeLane.ResetTouchState();

                            // 切换到新轨道
                            fingerToLaneMap[finger] = newLane;
                            newLane.OnTouchFromInput();
                        }
                        else
                        {
                            // 同轨道上滑动
                            activeLane.OnTouchHold();
                        }
                    }
                }
                else
                {
                    // 手指移出所有轨道
                    activeLane.OnTouchUp();
                    fingerToLaneMap.Remove(finger);
                }
            }
        }
        else
        {
            // 原地滑动
            activeLane.OnTouchHold();
        }
    }

    private void HandleFingerUp(Finger finger)
    {
        // 判断 Flick（优先判断）
        LaneController flickLane = null;
        if (fingerToLaneMap.TryGetValue(finger, out LaneController lane))
        {
            flickLane = lane;
            lane.OnTouchUp();
        }

        if (fingerSwipeData.TryGetValue(finger, out FingerSwipeInfo info))
        {
            Vector2 endPos = finger.screenPosition;
            float endTime = Time.time;

            float distance = Vector2.Distance(endPos, info.startPos);
            float duration = endTime - info.startTime;

            if (distance >= flickMinDistance && duration <= flickMaxDuration)
            {
                // flickLane 在这里仍然存在
                flickLane?.OnFlickFromInput();
            }

            fingerSwipeData.Remove(finger);
        }

        // 最后再移除
        fingerToLaneMap.Remove(finger);
    }



}
